package com.woniu.woniu_bx.controller;

import com.woniu.woniu_bx.pojo.Chat;
import com.woniu.woniu_bx.pojo.PageBean;
import com.woniu.woniu_bx.pojo.ResponseEntity;
import com.woniu.woniu_bx.pojo.User;
import com.woniu.woniu_bx.service.ChatService;
import com.woniu.woniu_bx.service.UserService;
import com.woniu.woniu_bx.utils.DateUtil;
import com.woniu.woniu_bx.vo.ChatVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.input.buffer.PeekableInputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author:GuoHai
 * @program: IntelliJ IDEA
 * @data: 2022/9/1 14:38
 */
@Slf4j
@RestController
@Validated
@RequestMapping("/chat")
public class ChatController {
    @Autowired
    private ChatService chatService;
    @Resource
    private UserService userService;
    @Resource
    private ChatVo chatVo;

   /**
    * @Description 查询最新的聊天记录
    * @Author 魏才林
    * @Param [chatVo] 参数需要传sendId，acceptId，pageNum
    * @return com.woniu.woniu_bx.pojo.ResponseEntity
    **/
    /**
     * 进入私聊页面时调用该接口，初始化私聊界面，展示聊天记录
     *
     * @param myId
     * @param otherId
     * @return
     */
    @GetMapping("/showChatRecord/{myId}/{otherId}")
    public ResponseEntity showChatRecord(@PathVariable int myId, @PathVariable int otherId) {
        List<Chat> chatList = chatService.findChatList(myId, otherId);
        for (Chat chat : chatList) {
            try {
                chat.setLocalTime(DateUtil.getLogicTime(chat.getTime(), "yyyy-MM-dd HH:mm:ss"));
            } catch (ParseException e) {

            }
        }
        chatVo.setChatList(chatList);
        chatVo.setSendUser(userService.getById(myId));
        chatVo.setAcceptUser(userService.getById(otherId));
        return ResponseEntity.SUCCESS("展示聊天记录成功", chatVo);
    }

    /**
     * @return com.woniu.woniu_bx.pojo.ResponseEntity
     * @Description 查询聊天记录
     * @Author 魏才林
     * @Param [chatVo] 参数需要传sendId，acceptId，pageNum
     **/
    @PostMapping("/getChatRecord")
    public ResponseEntity getChatRecord(@RequestBody ChatVo chatVo) {
        //默认展示跟10个人的聊天信息记录
        Integer pageSize = 10;

        //判断如果前端没有传页码，则默认查询最近的前10条记录
        if (chatVo.getPageNum() == null || chatVo.getPageNum() <= 0) {
            chatVo.setPageNum(1);
        }

        PageBean<Chat> chatPageBean = chatService.getChatRecord(chatVo.getSendUser().getId(),
                chatVo.getAcceptUser().getId(), pageSize, chatVo.getPageNum());

        List<Chat> chatList = chatService.findChatListUnRead(chatVo.getSendUser().getId(),  chatVo.getAcceptUser().getId());

        for(Chat chat :chatList){
            chat.setReaded("y");
            chatService.updateById(chat);
        }
        //由于查出来的数据，是根据最近时间来倒序的，从而查出最新的10条消息记录
        // 所以这里将查出的数据，再倒序一下，使其按照时间的升序来进行来进行排列
        Collections.reverse(chatPageBean.getData());

        return ResponseEntity.SUCCESS("展示聊天记录成功", chatPageBean);
    }

    /**
     * 根据用户id获取消息列表
     *
     * @param id
     * @return
     */
    @GetMapping("/getChatList/{id}")
    public ResponseEntity<List<User>> getChatList(@PathVariable int id) {
        List<Integer> chatList = chatService.getChatList(id);
        List<User> accptUsers = new ArrayList<>();
        for (Integer acceptId : chatList) {
            User accptUser = userService.getById(acceptId);
            List<Chat> chatDetail = chatService.findChatList(id, acceptId);
            Chat chat = chatDetail.get(0);
            Integer sumUnReadChatNum = chatService.getSumUnReadChatNum(acceptId, id);
            chat.setSumUnReadChatNum(sumUnReadChatNum);
            try {
                chat.setLocalTime(DateUtil.getLogicTime(chat.getTime(), "yyyy-MM-dd HH:mm:ss"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            accptUser.setChat(chat);
            accptUsers.add(accptUser);
        }
        return ResponseEntity.SUCCESS("展示聊天列表成功", accptUsers);
    }

    /**
     * 发送消息时调用该接口，返回值为true时表示聊天记录成功进入数据库，则在接收方页面展示接收到的内容
     *
     * @param chat
     * @return
     */
    @PostMapping("/sendMsg")
    public ResponseEntity sendMsg(Chat chat) {
        boolean isOk = chatService.save(chat);
        return ResponseEntity.SUCCESS("发送消息成功", isOk);
    }

}
